from sqlalchemy.orm import Session
from ..database.db import get_db
from captcha.image import ImageCaptcha
from pydantic import BaseModel,Field
from typing import Optional, Union, List,Any
from fastapi import (APIRouter, BackgroundTasks,Path,Form,
                     HTTPException,status,Request,Depends,Header,Cookie,Response,Query,Body)

from fastapi.security import OAuth2PasswordBearer,OAuth2PasswordRequestForm
import uuid
import base64
import time

from ..utils.auth_ import generate_captcha_text
from ..redisbase.redis_operations import set_key,get_key
from io import BytesIO
from ..crud.user_crud import get_user_by_name, create_user, create_user1
from passlib.hash import argon2
from ..utils.jwt_handler import create_token,get_username,get_user_token
from ..schemas.base import ResponseModel
from ..models.user_model import Users
from ..crud.folder_crud import create_folder
from ..models.usage_model import Usage

from ..crud.usage_crud import create_usage
from ..redisbase.redis_operations import get_hash_data,get_hash_field,delete_hash_key

admin=APIRouter(prefix="/auth", tags=["鉴权"])

@admin.get("/")
async def get_auth():
    return {"message":"auth"}

class CaptureModel(BaseModel):
    code: int
    data:dict

@admin.get("/captcha",response_model=CaptureModel)
async def get_captcha():
    """
    # 获取验证码
    * return:验证码图片
    """
    image = ImageCaptcha()
    text = generate_captcha_text()
    captcha_id=str(uuid.uuid4())

    set_key(captcha_id,text,300)  # 设置验证码，过期时间5分钟

    img_bytes = image.generate(text)
    buffered = BytesIO()
    img_bytes.seek(0)  # 确保指针在开头
    buffered.write(img_bytes.read())
    img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')

    # return StreamingResponse(content=img_bytes, media_type="image/png")
    return {
        "code": 200,
        "message": "success",
        "data": {
            "captcha_img":img_base64,
            "captcha_id": captcha_id,
            "text":text
        },
         # 可选：返回验证码ID供前端使用
    }



class LoginRequest(BaseModel):
    username: str
    password: str
    captcha_id: str
    captcha: str

@admin.post("/login")
async def loginIn(form_data: OAuth2PasswordRequestForm = Depends(),
                  # captcha_id: str = Form(...),
                  # captcha: str = Form(...),
                  db: Session = Depends(get_db)):
    username = form_data.username
    password = form_data.password

    # _captcha = get_key(captcha_id)
    #
    user=get_user_by_name(db,username)
    # if _captcha != captcha:
    #     return {
    #         "code": 411,
    #         "message": "验证码错误",
    #         "data": None,
    #         # "originUrl": str(request.url)
    #     }
    # if not user or not bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')):
    # if not user or user.password != password:
    if not user or not argon2.verify(password, user.password):
        return {
            "code": 412,
            "message": "用户名或密码错误",
            "data": None,
            # "originUrl": str(request.url)
        }
    else:
        user_token = create_token({"username": username})
        return {
            "code": 200,
            "message": "OK",
            "access_token": user_token,
            "token_type": "bearer"
            # "originUrl": str(request.url.path)
        }

class RegisterModel1(BaseModel):
    username: str
    password: str
    permissions:Optional[int] = 1

    class Config:
        orm_mode = True

class RegisterModel(BaseModel):
    username: str
    password: str
    captcha_id: str
    captcha: str


@admin.post("/register",response_model=ResponseModel)
async def userRegister(register_request: RegisterModel= Body(...),db: Session = Depends(get_db)):
    # request_data = await login_request.json()
    username = register_request.username
    password = register_request.password
    hashed_password =argon2.hash(password)
    # hashed_password=password
    captcha_id = register_request.captcha_id
    captcha = register_request.captcha
    _captcha = get_key(captcha_id)
    # if _captcha != captcha:
    #     return {
    #         "code": 411,
    #         "message": "验证码错误",
    #         "data": None,
    #         # "originUrl": str(request.url)
    #     }
    # else:
    if True:
        user = Users(username=username, password=hashed_password)
        a = create_user1(db, user).id
        print(a)
        create_folder(db, name="总文件夹", parent_id=None, user_id=a)
        return {
            "code": 200,
            "message": "Successfully registered",
            "data": a
        }



# async def get_current_user(token: str = Depends(OAuth2PasswordBearer(tokenUrl="token"))):
#     if get_key(token)==None:
#         raise HTTPException(
#             status_code=status.HTTP_401_UNAUTHORIZED,
#             detail="Token has been revoked"
#         )
#     credentials_exception = HTTPException(
#         status_code=status.HTTP_401_UNAUTHORIZED,
#         detail="Could not validate credentials",
#         headers={"WWW-Authenticate": "Bearer"},
#     )
#     try:
#         payload = get_user_token(token)
#         id: int = payload.get("id")
#         if id is None:
#             raise credentials_exception
#     except JWTError:
#         raise credentials_exception
#     return id

@admin.post("/logout",response_model=ResponseModel)
async def logout(username: str = Depends(get_username),
                 db: Session = Depends(get_db),):

    user = get_user_by_name(db, username).as_dict()
    user_id = user["id"]
    if not get_hash_data(user_id):
        return {
            "code": 204,
            "message": "Successfully logged out",
            "data": None
        }

    video_quantity=get_hash_field(user_id,"video_quantity")
    image_quantity=get_hash_field(user_id,"image_quantity")
    voice_quantity=get_hash_field(user_id,"voice_quantity")
    ppt_quantity=get_hash_field(user_id,"ppt_quantity")
    questions_quantity=get_hash_field(user_id,"questions_quantity")

    # current_date = time.strftime("%Y-%m-%d", time.localtime())
    # print("当前日期:", current_date)
    usage_info=Usage(user_id=user_id,
                         video_quantity=video_quantity,
                         image_quantity=image_quantity,
                         voice_quantity=voice_quantity,
                         ppt_quantity=ppt_quantity,
                         questions_quantntity=questions_quantity,
                         data=time.strftime("%Y-%m-%d", time.localtime()),


    )
    usage_date=create_usage(db,usage_info)

    delete_hash_key(user_id)
    return {
        "code":204,
        "message": "Successfully logged out",
        "data":None
    }

